package com.woniuxy.hrp.service.Serviceimpl;

import com.alibaba.fastjson.JSON;
import com.woniuxy.hrp.entity.Hospital;
import com.woniuxy.hrp.entity.Nat;
import com.woniuxy.hrp.mapper.NatMapper;
import com.woniuxy.hrp.service.NatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class NatServiceImpl implements NatService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NatMapper natMapper;

    @Override
    public void add(Nat nat) {
        natMapper.insert(nat);
    }

    @Override
    public Nat seleByH(Hospital hospital) {



        return natMapper.seleByHosp(hospital);
    }

    @Override
    public List<Nat> seleAll() {

        if ( redisTemplate.opsForList().range("nats",0,redisTemplate.opsForList().size("nats")).size() == 0 ) {
            System.out.println("没有发现缓存进入数据库查找");
            List<Nat> nats = natMapper.seleAll();
            List<String>  jsonnats=new ArrayList<>();
            nats.forEach(d->{
                jsonnats.add(JSON.toJSONString(d));
            });
            redisTemplate.opsForList().leftPushAll("nats",jsonnats);
            return  nats;
        }else{
            System.out.println("发现缓存无需查找");
            List<Nat> nats =new ArrayList<>();
            redisTemplate.opsForList().range("nats",0,redisTemplate.opsForList().size("nats")).forEach(r->{
                nats.add(JSON.parseObject((String) r,Nat.class));
            });
            return nats;
        }



    }
}
